#pragma once

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <unordered_set>
#include <string>
#include "unistd.h"

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

class Command
{
private:
    bool CheckSafe(const char *cmd)
    {
        for(auto& _cmd : _safe_cmd)
        {
            if(strncmp(_cmd.c_str(), cmd, _cmd.size()) == 0)
            {
                return 1;
            }
        }
        return 0;
    }

public:
    Command()
    {
        _safe_cmd.insert("ls");
        _safe_cmd.insert("touch");
        _safe_cmd.insert("which");
        _safe_cmd.insert("whoami");
        _safe_cmd.insert("pwd");
    }

    std::string Execute(const char *cmd)
    {
        if (!CheckSafe(cmd))
        {
            return "unsafe!";
        }
        std::string ret;
        char line[1024];
        FILE *fd = popen(cmd, "r");
        if (fd)
        {
            while (fgets(line, sizeof(line), fd))
            {
                ret += line;
            }
            return ret.empty() ? "success" : ret;
        }
        return "popen error";
    }

    void HandlerCommand(int sockfd, InetAddr &addr)
    {
        while (1)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo = Execute(buffer);
                write(sockfd, echo.c_str(), echo.size());
                // LOG(INFO, "echo success\n");
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }
    }

    ~Command()
    {
    }

private:
    std::unordered_set<std::string> _safe_cmd;
};
